<template>
  <div class="box">
    <hu-card :pb='0' v-show="MixinSelectShow">
      <el-form :model="queryParams" ref="queryForm"  label-width="110px">
        <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="标题" prop="title">
              <el-input v-model="queryParams.title" style="width: 100%" placeholder="请输入标题"   @keyup.enter.native="searchList" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公告类型" prop="type">
              <el-select  multiple collapse-tags   style="width: 100%" v-model="queryParams.types" placeholder="请选择公告类型">
                <el-option v-for="dict in dict.type['notice-type']" :key="dict.value" :value="dict.value" :label="dict.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公告等级" prop="grade">
              <el-select style="width: 100%"  multiple  collapse-tags  v-model="queryParams.grades" placeholder="请选择公告等级">
                <el-option v-for="(dict, index) in dict.type['notice-grade']" :key="dict.value" :value="dict.value" :label="dict.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="0" style="float: right">
              <el-button style="font-size: 14px;"  type="primary" icon="el-icon-search" @click="searchList">搜索</el-button>
              <el-button icon="el-icon-refresh"  @click="resetQuery" style="font-size: 14px;margin-left:10px">重置</el-button><cut-is-show :CutisShow.sync="MixinShowSearch"></cut-is-show>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="50" v-show="MixinShowSearch">
          <el-col :span="6">
            <el-form-item label="公开" prop="isOpen">
              <el-select  style="width: 100%"  v-model="queryParams.isOpen" placeholder="请选择公开">
                <el-option :value="1" label="是" />
                <el-option :value="2" label="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="置顶" prop="isTopping">
              <el-select  style="width: 100%"  v-model="queryParams.isTopping" placeholder="请选择置顶">
                <el-option :value="1" label="是" />
                <el-option :value="0" label="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布时间" prop="pickerValue">
              <el-date-picker @change="getPicker" v-model="pickerValue" style="width: 100%" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </hu-card>
    <hu-card>
      <el-row :gutter="10" class="mb8 space_between" type="flex">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus"  @click="handleAdd" style="font-size: 14px;">发布公告</el-button>
          <el-button style="font-size: 14px;margin-left:10px" type="danger" icon="el-icon-delete"  :loading="MixinLoading" @click="handleAllDelete">批量删除</el-button>
        </el-col>
        <right-toolbar :tableCol.sync="tableCol" :CutShowSearch.sync="MixinSelectShow" @queryTable="getList"></right-toolbar>
      </el-row>
      <hu-table :tableData="tableData" :loading="loading" :tableCol="tableCol" index selection @selection-change="handleSelectionChange">
        <template v-slot:content="{ row }">
          <el-button type="text" @click="check(row)">预览</el-button>
        </template>
        <template v-slot:isOpen="{ row }">
          <el-switch :value="row.isOpen == 1" @change="amendIsOpen($event, row)" active-color="#13ce66" inactive-color="#888888">
          </el-switch>
        </template>
        <template v-slot:isTopping="{ row }">
          <el-checkbox :value="!!row.isTopping" @change="amendIsTopping($event, row)"></el-checkbox>
        </template>
        <template v-slot:operate="{ row }">
          <el-button type="text" @click="handleUpdate(row)">修改</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </hu-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </hu-card>

    <hu-modal :title="formData.id ? '修改-公告' : '新增-公告'" :show-modal.sync="addModal" :loading="MixinLoading" @submit="addFrom">
      <!-- tent sta -->
      <el-form ref="formData1" :model="formData" :rules="rulesSon" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input class="inpues" style="font-size: 30px; font-weight: bold; color: #b5b5b5; height: 72px" v-model="formData.title" maxlength="50" minlength="2" :rows="10" placeholder="请输入公告标题（2～50个字）" />
        </el-form-item>
        <el-form-item prop="content" label="公告内容">
          <editor v-model="formData.content" :minHeight="150"></editor>
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="公告类型" prop="type">
              <el-select    style="width: 100%" v-model="formData.type" placeholder="请选择公告类型">
                <el-option v-for="dict in dict.type['notice-type']" :key="dict.value" :value="dict.value + ''" :label="dict.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="公告等级" prop="grade">
              <el-select    style="width: 100%" v-model="formData.grade" placeholder="请选择公告等级">
                <el-option v-for="dict in dict.type['notice-grade']" :key="dict.value" :value="dict.value + ''" :label="dict.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="定时发布" prop="createDate">
              <el-date-picker v-model="formData.createDate" style="width: 100%" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="4">
            <el-form-item label="公开" prop="isOpen">
              <el-radio-group v-model="formData.isOpen">
                <el-radio value="是" :label="1">是</el-radio>
                <el-radio value="否" :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="置顶" prop="isTopping">
              <el-checkbox :value="!!formData.isTopping" @change="formTopping"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="13">
            <el-form-item label="封面" prop="fileList">
              <el-upload class="upload-demo" :action="this.httpUrl + 'base/file/upload'" :on-remove="removeFile1" :headers="myHeaders" multiple :limit="1" :on-preview="lookFile" :on-exceed="handleExceed1" :on-success="successFile1" :file-list="fileList1">
                <el-button  type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传<b style="color: #f56c6c">.jpg, .png</b>文件
                  <!-- ，且不超过<b style="color: #f56c6c">5GB</b> -->
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="附件" prop="fileList">
              <el-upload class="upload-demo" :action="this.httpUrl + 'base/file/upload '" :on-remove="removeFile2" :headers="myHeaders" multiple :limit="999" :on-preview="lookFile" :on-exceed="handleExceed2" :on-success="successFile2" :file-list="fileList2">
                <el-button  type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传<b style="color: #f56c6c">.rar, .zip, .doc, .docx, .pdf, .jpg, .xls, .xlsx</b>文件
                  <!-- ，且不超过<b style="color: #f56c6c">5GB</b> -->
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </hu-modal>
    <hu-modal title="公告详情" :show-modal.sync="getModal" :loading="MixinLoading" :submit="false">
      <!-- slot="footer" -->
      <div style="color: #565656">
        <div style="
            font-size: 30px;
            font-weight: bold;
            line-height: 60px;
            text-align: center;
          ">
          {{ itemData.title }}
        </div>
        <div style="text-align: center; width: 100%; border-bottom: 1px solid #ddd">
          <p>
            <span style="color: #aeaeae; padding-left: 0px">发布单位：{{ itemData.createCompanyName }}</span>
            <span style="color: #aeaeae; padding-left: 30px">发布人：{{ itemData.createByName }}</span>
            <span style="padding-left: 30px; color: #aeaeae">已读人数：{{ itemData.lookCount }}</span>
            <span style="padding-left: 30px; color: #aeaeae">重要等级：{{ itemData.gradeName }}</span>
            <span style="padding-left: 30px; color: #aeaeae">时间：{{ itemData.createDate }}</span>
          </p>
        </div>
        <div>
          <el-form :model="itemData" ref="queryForm" class="mt10" :inline="true" label-width="110px" >
            <el-form-item label="附件下载" prop="grade">
              <template v-if="itemData.attachFiles">
                <span v-for="(item, index) in itemData.attachFiles" :key="index" style="display: flex; align-items: center">
                  <el-button @click="checkFile1(item)" type="text">{{
                    item.originalName
                  }}</el-button>
                  <i @click="downloadFile(item.previewPath)" class="el-icon-download i_icon" style="cursor: pointer; color: #496dff; font-size: 18px"></i>
                </span>
              </template>
            </el-form-item>
          </el-form>
        </div>
        <div style="display: flex; align-items: center;">
          <div style="margin: 0 10px">{{ itemData.createTime }}</div>
          <div>{{ itemData.createUserName }}</div>
        </div>
        <div style="width: 100%;padding: 0 90px ">
          <div class="ql-editor content-detail" style="word-wrap: break-word; word-break: normal" v-html="itemData.content">
          </div>
        </div>
        <!-- 9个小时 -->
        <!-- 11， 12， 1， 2， 3， 4， 5，6， 7， 8 -->
      </div>
    </hu-modal>
  </div>
</template>
<script>
// 富文本组件
import Editor from "@/components/Editor"
import {
  getList,
  addList,
  updateList,
  deleteList,
  topping,
  cancelTopping,
} from "@/api/help/issue";
import { getToken } from "@/utils/auth";
import configS from "@/utils/config";
import { setTimeout } from "timers";
export default {
  name: "NoticeIssueList",
  dicts: ["notice-type", "notice-grade"],
  components: {
    Editor
  },
  data() {
    return {
      isShow: false, // 切换搜索按键
      loading: true, // 加载
      // list 参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0, // table total
      // table Col
      tableCol: [
        {
          type: "selection",
          width: "55",
          show: true,
        },
        {
          title: "序号",
          type: "index",
          width: "55",
          showOverflowTooltip: false,
          show: true,
        },
        {
          title: "公告标题",
          key: "title",
          show: true,
        },
        {
          title: "公告类型",
          key: "typeName",
          show: true,
        },
        {
          title: "公告等级",
          key: "gradeName",
          show: true,
        },
        {
          title: "发布时间",
          key: "createDate",
          show: true,
        },
        {
          title: "发布人",
          key: "createByName",
          show: true,
        },
        {
          title: "发布单位",
          key: "createCompanyName",
          show: true,
        },
        {
          title: "公告内容",
          slot: "content",
          show: true,
        },
        {
          title: "已读人数",
          key: "lookCount",
          show: true,
        },
        {
          title: "置顶",
          slot: "isTopping",
          show: true,
        },
        {
          title: "公开",
          slot: "isOpen",
          show: true,
        },
        {
          title: "操作",
          width: "140",
          slot: "operate",
          fixed: "right",
          show: true,
        },
      ],
      tableData: [], // table Data
      addModal: false, // 弹窗
      // form Data
      formData: {
        isTopping: 1,
        isOpen: 1,
        attachFileId: [],
      },
      pickerValue: undefined, // 时间
      // 表单校验
      rulesSon: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "正文不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "公告类型不能为空", trigger: "change" },
        ],
        grade: [
          { required: true, message: "公告等级不能为空", trigger: "change" },
        ],
        createDate: [
          { required: true, message: "定时发布不能为空", trigger: "change" },
        ],
      },
      fileList1: [],
      fileList2: [],
      ids: [], // table 勾选项
      itemData: {},
      getModal: false,
      myHeaders: {},
      httpUrl: "",
      attachFileId: [], // 附件id,
      headFile: "", // 封面id
    };
  },
  created() {
    this.getList();
    this.setToken();
    this.httpUrl = configS.jBaseURL;
  },
  methods: {
    checkFile1(item) {
      this.$download.preview(item.previewPath, item.originalName);
    },
    downloadFile(url) {
      this.$download.download(url);
    },
    // 设置token
    setToken() {
      // 是否需要设置 token
      if (getToken()) {
        this.myHeaders["token"] = getToken();
      }
    },
    // 文件上传数量限制回调
    handleExceed1() {
      this.$message.error(`上传文件数量不能超过1个!`);
    },
    // 文件上传数量限制回调
    handleExceed2() {
      this.$message.error(`上传文件数量不能超过999个!`);
    },
    // 文件上传成功的回调
    successFile1(file) {
      this.headFile = file.result.id;
    },
    // 文件上传成功的回调
    successFile2(file) {
      this.attachFileId.push(file.result.id);
    },
    // 文件预览
    lookFile(file) {
      if (file.previewPath) {
        this.$download.preview(file.previewPath, file.originalName);
      } else {
        this.$modal.msgWarning("请上传成功后再预览文件");
      }
    },
    check(row) {
      this.itemData = row;
      this.getModal = true;
    },
    // reset 查询
    resetQuery() {
      this.pickerValue = undefined;
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
    },
    // 列表 List
    getList() {
      this.loading = true;
      this.MixinLoading = true;
      let params = {
        ...this.queryParams,
        types: this.queryParams.types && this.queryParams.types.join(","),
        grades: this.queryParams.grades && this.queryParams.grades.join(","),
      };
      getList(params).then(({ stateCode, result }) => {
        if (stateCode == 200) {
          this.loading = false;
          this.MixinLoading = false;
          this.tableData = result.records;
          this.total = result.total;
        }
      });
    },
    // 查询 list
    searchList() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 删除 | 导入文件
    resultFile(arr) {
      this.formData.file.push(arr[0]);
    },
    removeFile1(arr) {
      this.headFile = "";
    },
    removeFile2(arr) {
      let id = arr.response.result.id;
      let index = this.attachFileId.indexOf((res) => {
        return res == id;
      });
      this.attachFileId.splice(index, 1);
    },
    // 表单重置
    reset() {
      this.formData = {
        isTopping: 1,
        isOpen: 1,
        file: [],
        deleteId: [],
      };
      this.fileList1 = [];
      this.fileList2 = [];
      this.headFile = "";
      this.attachFileId = [];
    },
    // add 弹出
    handleAdd() {
      this.reset();
      setTimeout(() => {
        this.addModal = true;
      });
    },
    // Update 弹出
    handleUpdate(row) {
      this.reset();
      if (row.headFile) {
        this.fileList1 = [{ ...row.headFile, name: row.headFile.originalName }];
      }
      if (row.attachFiles) {
        row.attachFiles.forEach((res) => {
          this.fileList2.push({
            ...res,
            name: res.originalName,
          });
        });
      }
      this.formData = {
        id: row.id,
        title: row.title,
        content: row.content,
        type: row.type,
        grade: row.grade,
        isOpen: row.isOpen,
        createDate: row.createDate,
        isTopping: row.isTopping ? true : false,
        file: [],
        deleteId: [],
      };
      this.addModal = true;
    },
    // 提交
    addFrom() {
      this.$refs["formData1"].validate((valid) => {
        if (valid) {
          if (this.headFile != "") {
            this.$set(this.formData, "headFile", this.headFile);
          }
          if (this.attachFileId.length) {
            this.$set(this.formData, "attachFileId", this.attachFileId);
          }
          let params = {
            ...this.formData,
            isTopping: this.formData.isTopping ? 1 : 0,
            delFlag: "0",
          };
          let formData = new FormData();
          for (const key in params) {
            if (params[key]) {
              if (key == "file") {
                params[key].forEach((element) => {
                  formData.append(key, element.raw);
                });
              } else if (key == "deleteId") {
                if (params[key].length) {
                  formData.append(key, params[key].join(","));
                }
              } else {
                formData.append(key, params[key]);
              }
            }
          }
          formData.append("headFile", this.headFile);
          formData.append("attachFileId", this.attachFileId.join(","));
          this.MixinLoading = true;
          if (this.formData.id != undefined) {
            updateList(params)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.addModal = false;
                this.getList();
              })
              .finally(() => {
                this.MixinLoading = false;
              });
          } else {
            addList(params)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.addModal = false;
                this.getList();
              })
              .finally(() => {
                this.MixinLoading = false;
              });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.addModal = false;
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(() => {
          return deleteList(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
    },
    // add 是否置顶
    formTopping(value) {
      this.formData.isTopping = value ? 1 : 0;
    },
    // add 是否公开
    formIsOpen(value) {
      this.formData.isOpen = value ? 1 : 2;
    },
    amendIsOpen(value, row) {
      row.isOpen = value == 1 ? 1 : 2;
      this.formData = {
        id: row.id,
        title: row.title,
        content: row.content,
        type: row.type,
        grade: row.grade,
        createDate: row.createDate,
        isOpen: (row.isOpen = value == 1 ? 1 : 2),
        isTopping: row.isTopping ? 1 : 0,
        delFlag: "0",
      };
      updateList(this.formData).then((response) => {
        this.$modal.msgSuccess("修改成功");
      });
    },
    // 是否置顶
    amendIsTopping(value, row) {
      row.isTopping = value ? 1 : 0;
      if (value) {
        topping(row.id).then(({ result }) => {
          if (result) {
            this.$modal.notifySuccess("置顶成功");
            this.searchList();
          }
        });
      } else {
        cancelTopping(row.id).then(({ result }) => {
          if (result) {
            this.$modal.notifySuccess("取消置顶");
            this.searchList();
          }
        });
      }
    },
    // 搜索时间
    getPicker(arrDate) {
      this.queryParams.beginTime = arrDate ? arrDate[0] : undefined;
      this.queryParams.endTime = arrDate ? arrDate[1] : undefined;
    },
    // 多选框 table
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    // 删除勾选
    handleAllDelete() {
      if (!this.ids.length) return this.$modal.msg("请勾选表格");
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(() => {
          return deleteList(this.ids.join(","));
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .inpues > .el-input__inner {
  height: 100% !important;
}
.box-card[data-v-6e93a3a0] .el-form--inline .el-form-item {
  margin-bottom: 10px !important;
}
::v-deep .ql-editor {
  line-height: 1.8 !important;
}
</style>
